$(function() {
    $('#tb_ads').bootstrapTable({
        method: 'POST',                      //请求方式（*）
        url:projectPath + "/base/workorders/todoList",
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search:false,
        queryParams: dataQueryParams,//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10,20,50],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "id",
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //显示刷新按钮
        showToggle: true,
        minimumCountColumns: 12,             //最少允许的列数
        singleSelect:true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            {field: 'check', checkbox: true},
            {field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                var pageSize=$('#tb_ads').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber=$('#tb_ads').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }},
            {field: 'uuid', title: '主键', align: 'center', visible:false},
            {field: '', title: '资产码/批次号',align: 'center',formatter: function (value, row, index) {
                if(row.targettype == "registrationApply"){ // 注册码
                    value = row.registrationApplyNo
                }else {
                    value = row.stakeNo
                }
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'workorderno', title: '工单编号',align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'content', title: '工单类型',align: 'center',formatter: function (value, row, index) {
                return '<div style="white-space: nowrap;"><a href="javascript:;" onclick="workOrderDetail(\''+row.targettype+'\',\''+row.workstatus+'\',\''+row.targetuuid+'\',\''+row.uuid+'\')">' + value + '</a></div>';
            }},
            {field: 'createorgName', title: '申请/产权单位',align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'createdat', title: '创建时间',align: 'center',formatter: function (value, row, index) {
                if(value == "" || value == null){
                    value="";
                }else{
                    value = getLocalTime(value);
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'workstatus', title: '当前状态', align: 'center',formatter: function (value, row, index) {
                if(row.targettype == "registrationApply"){ // 注册码
                    if(value == 10001){
                        value = "待审核"
                    }else if(value == 10004){
                        value = "审核拒绝"
                    }else if(value == 10005){
                        value = "审核通过"
                    }
                }else if(row.targettype == "maintenanceApply"){ // 桩维护
                    if(value == 10001){
                        value = "资产台账待维护"
                    }else if(value == 10002){
                        value = "已提交(待审核)"
                    }else if(value == 10005){
                        value = "审核已通过"
                    }
                }else if(row.targettype == "maintenaceCharge"){ // 桩审核
                    if(value == 10001){
                        value = "待审核"
                    }else if(value == 10004){
                        value = "审核拒接"
                    }else if(value == 10005){
                        value = "审核通过"
                    }
                }
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
        ],
        responseHandler: function (data) {
            return {
                total:data.data.total,
                rows:data.data.list
            }
        }
    });
    // 置空
    $("#btnEmpty").on("click",function(){
        $("#workorderNo").val("");
        $("#startTime").val("");
        $("#endTime").val("");
        $("#targetType").val("");
        $("#createorgCode").attr("data-id","");
        $("#createorgCode").val("");
    });
    // 工单查询
    $("#btnQuery").on("click",function () {
        $('#tb_ads').bootstrapTable('refresh', {url: projectPath+"/base/workorders/todoList",pageNumber:1});
    });
    // 设备型号按钮查询
    $("#btnQueryEquipment").click(function(){
        $('#equipment_table').bootstrapTable('refresh', {url:projectPath + "/base/equipment/infos/list"});
    });
    $("#btnQueryStation").click(function(){
        $('#station_table').bootstrapTable('refresh', {url: projectPath+"/base/stations/list"});
    });
    //查询型号类型下拉列表
    selectList('typeinfo','30002000');
    //开始时间
    $('#startTime').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: 1,
        todayBtn: 1,
        initialDate:new Date(),
        startView: 2,
        minView: 2,
        forceParse: 0,
        pickerPosition:'bottom-right',
    }).on("changeDate",function(e){
        if(e.date != null&&e.date != ''){
            var startTime = Dateinit.getNextDay(e.date); //2018-03-10 14:47
        }
        //前一天与后一天时间的比较清空
        var start2 = new Date(Date.parse($('#startTime').val().replace(/-/g,"/"))); // 中国标准时间
        if(Date.parse(startTime.replace(/-/g,"/"))> start2){
            $("#endTime").val('');
        }
        //设置结束时间的起始值未开始时间的下一天
        $("#endTime").datetimepicker("setStartDate",startTime);
    });
    //结束时间
    $('#endTime').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: 1,
        todayBtn: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        pickerPosition:'bottom-right',
    });

    // 生产日期
    $('#createdat').datepicker({
        language:  'zh-CN',
        autoclose: true, //自动关闭
        // beforeShowDay: $.noop,    //在显示日期之前调用的函数
        calendarWeeks: false,     //是否显示今年是第几周
        clearBtn: false,          //显示清除按钮
        daysOfWeekDisabled: [],   //星期几不可选
        endDate: Infinity,        //日历结束日期
        forceParse: true,         //是否强制转换不符合格式的字符串
        format: 'yyyy-mm-dd',     //日期格式
        keyboardNavigation: true, //是否显示箭头导航
        // language: 'cn',           //语言
        minViewMode: 0,
        orientation: "auto",      //方向
        rtl: false,
        // startDate: -Infinity,     //日历开始日期
        startView: 0,             //开始显示
        todayBtn: true,          //今天按钮
        todayHighlight: true,    //今天高亮
        weekStart: 0              //星期几是开始
    });

    //工单类型下拉菜单
    $.get(projectPath + '/base/constss/list?code=1000000010', function (r) {
        var data = r.data;
        var value = '<option value="">--请选择--</option>';
        $(data).each(function(index,r){
            value += '<option value="'+r.constvalue+'">'+r.constname+'</option>';
        })
        $("#targetType").append(value);
    });

    // 产权单位弹窗选择
    $("#prorgcodeClick").on("click",function () {
        initOrgTreeLayer("0","选择产权单位","createorgCode");
    });
    initOrgSelects();
});
// 查询参数
function dataQueryParams() {
    var filterinfo = {};
    if($("#workorderNo").val() != ""){
        filterinfo.workorderNo = $("#workorderNo").val(); // 工单编号
    };
    if($("#startTime").val() != ""){
        filterinfo.createdAtStart = $("#startTime").val(); // 开始时间
    };
    if($("#endTime").val() != ""){
        filterinfo.createdAtEnd = $("#endTime").val(); // 结束时间
    };
    if($("#targetType").val() != ""){
        filterinfo.targetType = $("#targetType").val(); // 工单类型
    };
    if($("#createorgCode").attr("data-id") != ""){
        filterinfo.createorgCode = $("#createorgCode").attr("data-id"); // 产权单位
    };
    filterinfo.offset = (this.pageNumber-1)*this.pageSize;
    filterinfo.limit = this.pageSize;
    return filterinfo;
};


/*-----------------------------------------------注册码 桩 保存 提交 通过 拒绝 操作----------------------------------------*/

//停车区id改变触发重新查询停车位列表
$("#parkareauuid").on("change",function(){
    getSpaceList();
    if(spaceList.length >0){
        var tablist = nthTabs.getTabList();
        for (var i = 0;i<tablist.length;i++){
            $(tablist[i].id+" select[name='parkSpaceSelect']").empty();
            $(tablist[i].id+" select[name='parkSpaceSelect']").append("<option value=''>--请选择--</option>");
            $.each(spaceList,function(index, item){
                if(item.bindedCharger == "0"){
                    $(tablist[i].id+" select[name='parkSpaceSelect']").append("<option value='"+item.uuid+"'>"+item.name+"</option>");
                }else if(item.bindedCharger == "1"){
                    $(tablist[i].id+" select[name='parkSpaceSelect']").append("<option value='"+item.uuid+"' title='该停车位已绑定，不可选择！' style='background-color: red;' disabled>"+item.name+"</option>");
                };
            });
        }
    };
});

// 工单点击选择审核
$("#btnCheck").on("click",function () {
    var targettype = ""; //工单类型
    var workstatus = "" ;//工单状态
    var targetuuid = ""; //注册码或桩uuid
    var uuid = ""; // 工单uuid
    var p_n = $('#tb_ads').bootstrapTable('getData');
    if (p_n != null && p_n.length > 0) {
        var len = $('#tb_ads').bootstrapTable('getData').length;
        for (var i = 0; i < len; i++) {
            if ($('#tb_ads').bootstrapTable('getData')[i].check == true) {
                uuid = $('#tb_ads').bootstrapTable('getData')[i].uuid;
                targetuuid = $('#tb_ads').bootstrapTable('getData')[i].targetuuid;
                workstatus = $('#tb_ads').bootstrapTable('getData')[i].workstatus;
                targettype = $('#tb_ads').bootstrapTable('getData')[i].targettype;
            };
        };
        alert(workstatus);
        alert(targetuuid + "注册码或者桩id");
        alert(uuid + "工单本身id");
        if (uuid != '' && uuid != null) {
            // 选择工单之后的操作
            if(targettype == "registrationApply"){ // 注册码
                var indexReg = layer.open({
                    type: 1,
                    title: "注册码",
                    shadeClose: true,
                    shade: 0.3,
                    area: ['100%', '100%'],
                    skin: 'layui-layer-rims',
                    content: $(".registrationApply"),
                    closeBtn:1,
                    shadeClose:false,
                    fixed:false,
                    resize:true,
                    maxmin:true,
                    success:function(){
                        $("#acceptedAmount").prop("readonly",false);
                        $("#agreeMessage").prop("readonly",false);
                        if(workstatus == 10001){
                            $("#btnAgreeRegis").show();
                            $("#btnRejectRegis").show();
                        }else{
                            $("#btnAgreeRegis").hide();
                            $("#btnRejectRegis").hide();
                        };
                        regisDetail(targetuuid);
                    },
                    cancel:function(){
                        layer.close(indexReg);
                    }
                });
                // 关闭
                $("#btnCloseRegis").unbind().on("click",function(){
                    layer.close(indexReg);
                });
                // 通过
                $("#btnAgreeRegis").unbind().on("click",function () {
                    $.ajax({
                        type: "POST",
                        url:projectPath+'/base/workorders/registrationApplyAccept',
                        async:false,
                        dataType:"json",
                        // contentType:"application/json",
                        data:{
                            "uuid":uuid,
                            "reviewSuggestion":$("#agreeMessage").val(),
                            "acceptedAmount":$("#acceptedAmount").val()
                        },
                        success:function (data) {
                            if(data.code == "0"){
                                layerAlert.successMessage("审核通过","");
                            }else{ // TODO 失败了
                                layerAlert.errorMessage("审核失败");
                            }
                        },
                        error:function () {
                            layerAlert.errorMessage("数据错误,请联系管理员");
                        }
                    });
                    layer.close(indexReg);
                });

                // 驳回
                $("#btnRejectRegis").unbind().on("click",function () {
                    $.ajax({
                        type: "POST",
                        url:projectPath+'/base/workorders/registrationApplyReject',
                        async:false,
                        dataType:"json",
                        // contentType:"application/json",
                        data:{
                            "uuid":uuid,
                            "reviewSuggestion":$("#agreeMessage").val(),
                            "acceptedAmount":$("#acceptedAmount").val()
                        },
                        success:function (data) {
                            if(data.code == "0"){
                                layerAlert.successMessage("驳回成功","");
                            }else{// TODO 失败了
                                layerAlert.errorMessage("驳回失败");
                            }
                        },
                        error:function () {
                            layerAlert.errorMessage("数据错误,请联系管理员");
                        }
                    });
                    layer.close(indexReg);
                })
            }else if(targettype == "maintenanceApply"){ // 桩维护
                var indexApply = layer.open({
                    type: 1,
                    title: "充电桩维护申请",
                    shadeClose: true,
                    shade: 0.3,
                    area: ['100%', '100%'],
                    skin: 'layui-layer-rims',
                    content: $(".stakeSafeOrAudit"),
                    closeBtn:1,
                    shadeClose:false,
                    fixed:false,
                    resize:true,
                    maxmin:true,
                    success:function(){
                        if(workstatus == 10001){
                            $("#btnSave").show();
                            $("#btnSubmit").show();
                            $("#btnAgreeStake").hide();
                            $("#btnRejectStake").hide();
                            $("#stakeagree").hide();
                            $("#stakeAgree").parent().hide();
                        }else if(workstatus == 10002){
                            $("#btnSave").hide();
                            $("#btnSubmit").hide();
                            $("#btnAgreeStake").hide();
                            $("#btnRejectStake").hide();
                            $("#addChargingGunBtn").hide();
                            $("#stakeagree").hide();
                        };
                        stakeDetail(targetuuid);
                        $("#targetuuid").val(targetuuid);
                        $("#uuid").val(uuid);
                    },
                    cancel:function(){
                        layer.close(indexApply);
                    }
                });
                $("#btnCloseStake").unbind().on("click",function(){
                    layer.close(indexApply);
                });
            }else if(targettype == "maintenaceCharge"){ // 桩审核
                var indexCharge = layer.open({
                    type: 1,
                    title: "充电桩维护审核",
                    shadeClose: true,
                    shade: 0.3,
                    area: ['100%', '100%'],
                    skin: 'layui-layer-rims',
                    content: $(".stakeSafeOrAudit"),
                    closeBtn:1,
                    shadeClose:false,
                    fixed:false,
                    resize:true,
                    maxmin:true,
                    success:function(){
                        if(workstatus == 10001){
                            $("#btnSave").hide();
                            $("#btnSubmit").hide();
                            $("#btnAgreeStake").show();
                            $("#btnRejectStake").show();
                            $("#addChargingGunBtn").hide();
                            $("#stakeagree").show();
                            $("#stakeAgree").parent().show();
                        }else if(workstatus == 10002){
                            $("#btnSave").hide();
                            $("#btnSubmit").hide();
                            $("#btnAgreeStake").hide();
                            $("#btnRejectStake").hide();
                            $("#addChargingGunBtn").hide();
                        };
                        stakeDetail(targetuuid);
                    },
                    cancel:function(){
                        layer.close(indexCharge);
                    }
                });
                // 关闭
                $("#btnCloseStake").unbind().on("click",function(){
                    layer.close(indexCharge);
                });
                // 通过
                $("#btnAgreeStake").unbind().on("click",function(){
                    $.ajax({
                        type: "POST",
                        url:projectPath+'/base/workorders/maChargeAccept?workOrderUuid=' + uuid,
                        async:false,
                        dataType:"json",
                        contentType:"application/json",
                        data:JSON.stringify({workOrderUuid:uuid,xxx:$("#stakeAgree").val()}),
                        success:function (data) {
                            if(data.code == "0"){
                                layerAlert.successMessage("审核通过","");
                            }else{
                                layerAlert.errorMessage("审核失败");
                            }
                        },
                        error:function () {
                            layerAlert.errorMessage("数据错误,请联系管理员");
                        }
                    });
                    layer.close(indexCharge);
                });

                // 驳回
                $("#btnRejectStake").unbind().on("click",function(event){
                    $.ajax({
                        type: "POST",
                        url:projectPath+'/base/workorders/maChargeReject?workOrderUuid=' + uuid,
                        async:false,
                        dataType:"json",
                        contentType:"application/json",
                        data:JSON.stringify({workOrderUuid:uuid,xxx:$("#stakeagree").val()}),
                        success:function (data) {
                            if(data.code == "0"){
                                layerAlert.successMessage("驳回成功","");
                            }else{
                                layerAlert.errorMessage("驳回失败");
                            }
                        },
                        error:function () {
                            layerAlert.errorMessage("数据错误,请联系管理员");
                        }
                    });
                    layer.close(indexCharge);
                })
            }
        } else {
            layerAlert.errorMessage("您的选择为空");
        }
    };
});

// 工单详情跳转
function workOrderDetail(targettype,workstatus,targetuuid,uuid){
    if(targettype == "registrationApply"){ // 注册码
        var indexReg = layer.open({
            type: 1,
            title: "注册码",
            shadeClose: true,
            shade: 0.3,
            area: ['100%', '100%'],
            skin: 'layui-layer-rims',
            content: $(".registrationApply"),
            closeBtn:1,
            shadeClose:false,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
                $("#acceptedAmount").prop("readonly",true);
                $("#agreeMessage").prop("readonly",true);
                regisDetail(targetuuid);
                $("#btnAgreeRegis").hide();
                $("#btnRejectRegis").hide();
            },
            cancel:function(){
                layer.close(indexReg);
            }
        });
        // 关闭
        $("#btnCloseRegis").unbind().on("click",function(){
            layer.close(indexReg);
        });
    }else if(targettype == "maintenanceApply"){ // 桩维护
        var indexApply = layer.open({
            type: 1,
            title: "充电桩维护申请",
            shadeClose: true,
            shade: 0.3,
            area: ['100%', '100%'],
            skin: 'layui-layer-rims',
            content: $(".stakeSafeOrAudit"),
            closeBtn:1,
            shadeClose:false,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
                stakeDetail(targetuuid);
                $("#btnAgreeStake").hide();
                $("#btnRejectStake").hide();
                $("#btnSave").hide();
                $("#btnSubmit").hide();
            },
            cancel:function(){
                layer.close(indexApply);
            }
        });
        // 关闭
        $("#btnCloseStake").unbind().on("click",function(){
            layer.close(indexApply);
        });
    }else if(targettype == "maintenaceCharge"){ // 桩审核
        var indexCharge = layer.open({
            type: 1,
            title: "充电桩维护审核",
            shadeClose: true,
            shade: 0.3,
            area: ['100%', '100%'],
            skin: 'layui-layer-rims',
            content: $(".stakeSafeOrAudit"),
            closeBtn:1,
            shadeClose:false,
            fixed:false,
            resize:true,
            maxmin:true,
            success:function(){
                stakeDetail(targetuuid);
                $("#btnAgreeStake").hide();
                $("#btnRejectStake").hide();
                $("#btnSave").hide();
                $("#btnSubmit").hide();
            },
            cancel:function(){
                layer.close(indexCharge);
            }
        });
        // 关闭
        $("#btnCloseStake").unbind().on("click",function(){
            layer.close(indexCharge);
        });
    }
};


/* 注册码详情 */
function regisDetail(targetuuid){
    $.ajax({
        type: "POST",
        url:projectPath+'/base/registration/applys/detail?id='+targetuuid,
        async:false,
        dataType:"json",
        success:function(result){
            var data = result.data;
            $("#prorgcode").val(data.prorgcode); // 产权单位 申请人所在单位
            $("#apply").val(data.prorgcode); // 申请单位
            $("#creatorUuid").val(data.creatorname); // 申请人
            $("#applyAmount").val(data.amount); // 申请数量
            $("#acceptedAmount").val(data.amount); // 下发数量
            $("#stakeType").val(data.staketype); // 充电桩类型
            $("#remark").val(data.remark); // 申请备注

            // 电费
            var chargerfeemodelcode = data.chargerfeemodelcode;
            // 服务
            var servicefeemodelcode = data.servicefeemodelcode;
            getChargerfeemodelcode(chargerfeemodelcode);
            getServicefeemodelcode(servicefeemodelcode);
        },
        error:function(){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};

// 电费
function getChargerfeemodelcode(chargerfeemodelcode){
    $.ajax({
        type: "GET",
        url:projectPath+'/base/chargerfeemodels?id=' + chargerfeemodelcode,
        async:false,
        dataType:"json",
        contentType:"application/json",
        success:function(result){
            var data = result.data.list[0];
            if(result.data.list.length>0){
                $("#sharpFee").val(data.sharpfee);
                $("#sharpZone").val(data.sharpzone);
                $("#overShootFee").val(data.overshootfee);
                $("#overShootZone").val(data.overshootzone);
                $("#flatFee").val(data.flatfee);
                $("#flatZone").val(data.flatzone);
                $("#valleyFee").val(data.valleyfee);
                $("#valleyZone").val(data.valleyzone);
            }
        },
        error:function(){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};

// 服务费
function getServicefeemodelcode(servicefeemodelcode){
    $.ajax({
        type: "GET",
        url:projectPath+'/base/servicefeemodels?id=' + servicefeemodelcode,
        async:false,
        dataType:"json",
        contentType:"application/json",
        success:function(result){
            var data = result.data.list[0];
            if(result.data.list.length>0) {
                $("#serverSharpFee").val(data.sharpfee);
                $("#serverOverShootFee").val(data.overshootfee);
                $("#serverFlatFee").val(data.flatfee);
                $("#serverFalleyFee").val(data.valleyfee);
            }
        },
        error:function(){
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};



var nthTabs;
// 充电枪的添加
$(function(){
    var clickCount = 0;
    $("#addChargingGunBtn").click(function() {
        if(nthTabs == undefined || nthTabs == null){
            nthTabs = $("#editor-tabs").nthTabs();
        };
        if(nthTabs.getTabList().length >= 2){
            layerAlert.errorMessage("一桩只能绑定两个枪");
            return;
        };
        if(clickCount < 1){
            var uuid= "chargGunUuid" + Math.ceil(Math.random()*10); //uuid
            var addHtmlContent = '';
            addHtmlContent += '<div class="col-md-12" style="margin-top:20px;">';
            addHtmlContent += '<div class="col-md-12 form-group">';
            addHtmlContent += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">充电枪编号:</label><input type="text" name="chargNo" class="form-control" readonly></div>';
            addHtmlContent += '<div class=" col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">枪资产编码:</label><input type="text" name="assetNo" class="form-control" readonly></div>';
            addHtmlContent += '<div class=" col-md-4 col-sm-4 col-xs-4 "><label class="label-width4">设备接口类型:</label><select class="form-control" name="type"><option value="1">家用插座</option><option value="2">交流接口插座</option><option value="3">交流接口插头</option><option value="4">直流接口枪头</option></select></div>';
            addHtmlContent += '</div><div class="col-md-12 form-group">';
            addHtmlContent += '<div class="col-md-4 col-sm-4 col-xs-4"><label class="label-width1">关联停车位:</label><select class="form-control" name="parkSpaceSelect" style="border-radius: 4px 0px 0px 4px;width: 58%;"><option value=></option></select><button id="addParkSpaceClick" class="btn btn-info" style="border-radius: 0px 4px 4px 0px;vertical-align: top;width: 12%;"><i class="fa fa-plus"></i></button></div>';
            addHtmlContent += '</div></div>';
            nthTabs.addTab({
                id:uuid,
                title:"新增充电枪",
                content:addHtmlContent
            });
            nthTabs.setActTab(uuid);
            clickCount++;
        }else{
            layerAlert.errorMessage("一次只能新建一个枪");
        }
        // 添加充电枪对停车位的操作
        var tablist = nthTabs.getTabList();
        $("#"+uuid+" select[name='parkSpaceSelect']").empty();
        $("#"+uuid+" select[name='parkSpaceSelect']").append("<option value=''>--请选择--</option>");
        $.each(spaceList,function(index, item){
            if(item.bindedCharger == "0"){
                $("#"+uuid+" select[name='parkSpaceSelect']").append("<option value='"+item.uuid+"'>"+item.name+"</option>");
            }else if(item.bindedCharger == "1"){
                $("#"+uuid+" select[name='uuid']").append("<option value='"+item.uuid+"' title='该停车位已绑定，不可选择！' style='background-color: red;' disabled>"+item.name+"</option>");
            };
        });

        $("#addParkSpaceClick").prop("disabled",false).on("click",function(e){
            $(this).unbind(e);
            for (var i = 0;i<tablist.length;i++){
                $(tablist[i].id+" select[name='parkSpaceSelect']").parent().after('<div class="col-md-4 col-sm-4 col-xs-4"><label class="label-width1">新增停车位:</label><input type="text" class="form-control" name="newAddParkSpaceName"></div>');
            }
        });
    });
});

/* 桩详情 */
function stakeDetail(targetuuid){
    $.ajax({
        type: "POST",
        url:projectPath+'/base/stakes/detail?id='+targetuuid,
        async:false,
        dataType:"json",
        success:function (data) {
            debugger;
            result = data.data;
            $("#stakeNos").val(result.stakeno); // 桩编号
            $("#stakename").val(result.stakename); // 桩名称(字段中的别名)
            if(result.runtime == null || result.runtime == ""){
                $("#runtime").val(""); // 投运时间
            }else{
                $("#runtime").val(getLocalTime(result.runtime)); // 投运时间
            };
            $("#authcode").val(result.authcode); // 授权码
            $("#registrationNo").val(result.registrationNo); // 注册码
            if(result.useAt == null || result.useAt == ""){
                $("#registdat").val("");     // 注册时间
            }else{
                $("#registdat").val(getLocalTime(result.useAt));     // 注册时间
            };
            if (result.productionDate == null || result.productionDate == "") {
                $("#createdat").val(""); // 生产时间
            } else {
                $("#createdat").val(getLocalTime(result.productionDate)); // 生产时间
            };
            $("#factoryno").val(result.outFactoryDateNo);                    // 出厂编号
            $("#durableyears").val(result.durableYears); //使用年限
            $("#stakeTypes").val(result.staketype); // 桩类型(公专)
            $("#typeinfo").val(result.type); // 设备类型
            $("#status").val(result.status); // 桩标记
            // 接口标准初始化
            if (result.type == "1") { // 直流
                $.ajax({
                    type: "get",
                    async:false,
                    url: projectPath + '/base/constss/list?code=30005052',
                    success:function (data) {
                        debugger;
                        console.log(data);
                        $("#standard").empty();
                        $("#standard").append('<option value="">--请选择--</option>');
                        $("#standard").append('<option value="'+ data.data[0].constvalue +'">'+ data.data[0].constname +'</option>');
                    }
                });
            } else if (result.type == "2") { // 交流
                $.ajax({
                    type: "get",
                    async:false,
                    url: projectPath + '/base/constss/list?code=30005051',
                    success:function (data) {
                        debugger;
                        console.log(data);
                        $("#standard").empty();
                        $("#standard").append('<option value="">--请选择--</option>');
                        $("#standard").append('<option value="'+ data.data[0].constvalue +'">'+ data.data[0].constname +'</option>');
                    }
                });
            };
            if(result.debuggingtime == null || result.debuggingtime == ""){
                $("#debuggingtime").val(""); // 调试时间
            }else{
                $("#debuggingtime").val(getLocalTime(result.debuggingtime)); // 调试时间
            };
            debugger;
            $("#standard").val(result.standard);



            $("#standards").selectpicker('val', result.chargeStandard); // 充电标准
            $('#standards').selectpicker('refresh');

            debugger;
            var tradetypes = result.tradetypes;
            var groupCheckbox = $("input[name='tradeTypes']");
            for (var i = 0; i < groupCheckbox.length; i++) {
                if (isInArray(tradetypes, groupCheckbox[i].value)) {
                    groupCheckbox[i].checked = true;
                    groupCheckbox[i].disabled = false;
                }
            }; // 交易类型



            // 获取站设备停车位uuid为后续传值获取详情
            var stationuuid = result.stationuuid;
            var equipmodeluuid = result.equipmodeluuid;
            var parkingareauuid = result.parkingareauuid;
            getStationTemplate(stationuuid);
            getEquipmentTemplate(equipmodeluuid);
            getParkAreaTemplate(parkingareauuid);
            getChargeGunTemplate(targetuuid);
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
}

// 站详情
function getStationTemplate(stationuuid){
    if(stationuuid == null || stationuuid == "" ){
        return;
    };
    // 站信息回显
    $.ajax({
        type: "GET",
        url:projectPath+'/base/stations/'+stationuuid,
        async:false,
        dataType:"json",
        success:function (data) {
            var result = data.data;
            $("#stationnameInfo").val(result.stationname); // 站名称
            $("#stationnameInfo").attr("uuid",result.uuid); // 站名称

            $("#provinceCityPartInfo").val(result.partOrgName); // 组织机构
            $("#address").val(result.address); // 站地址
            $("#isthird").val(result.isthird); // 三方
            $("#stationType").selectpicker('val',((result.isthird==0||result.isthird==1)?"0":"1")+"-"+result.stationtype); // 站点类型
            $('#stationType').selectpicker('refresh');

            $("#lat").val(result.lat); // 经度
            $("#lng").val(result.lng); // 纬度
            $('#operatoruuid').selectpicker('val', result.operatoruuid);//运营商设置选中
            $('#operatoruuid').selectpicker('refresh');

            $("#servicephone").val(result.servicephone); // 服务电话
            $("#prorgCode").val(result.prOrgName); // 产权单位
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
};

// 设备型号详情
function getEquipmentTemplate(equipmodeluuid){
    // 设备型号信息回显
    $.ajax({
        type: "POST",
        url: projectPath + '/base/equipment/infos/detail?id=' + equipmodeluuid,
        async:false,
        dataType:"json",
        success:function (data) {
            result = data.data;
            if(result != null){
                $("#equipmentno").val(result.equipmentname); //设备型号
                $("#vendoruuid").val(result.vendorName); //生产厂商
                $("#vendoruuid").attr("datauuid",result.vendoruuid);
                $("#maxoutvolt").val(result.maxoutvolt); //最大电压
                $("#power").val(result.power); //额定功率
            }
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    })
};

// 停车区详情
function getParkAreaTemplate(parkingareauuid){
    // 停车区信息回显
    $.ajax({
        type: "POST",
        url:projectPath+'/base/parking/areas/detail?id='+parkingareauuid,
        async:false,
        dataType:"json",
        success:function (data) {
            var result = data.data;
            if(result || result != null) {
                $("#parkAreaNameInfo").val(result.name);// 选择停车区
                $("#parkareauuid").val(result.uuid); // 区uuid
                $("#parkingfee").val(result.parkingfee); // 收费标准
                $("#openat").val(result.openat); // 开放时间
                $("#closeat").val(result.closeat); //关闭时间
                $("#parkareauuid").change();
            }
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
};

// 充电枪详情
function getChargeGunTemplate(targetuuid){
    // 充电枪信息回显
    nthTabs = $("#editor-tabs").nthTabs({allowClose:false});
    $.ajax({
        type: "POST",
        url:projectPath+'/base/chargers/queryChargersByStakeUuid?stakeUuid='+targetuuid,
        async:false,
        dataType:"json",
        success:function (data) {
            var result = data.data;
            console.log(result)
            if (result || result != null){
                if(spaceList == null){
                    getSpaceList();
                };
                if(equTypeList == null){
                    getEquTypeList();
                }
                for(var i = 0, length1 = result.length; i < length1; i++){
                    var dataHtml = '';
                    dataHtml += '<div class="col-md-12" style="margin-top: 20px;">';
                    dataHtml += '<div class="col-md-12 form-group"> <input type="hidden" name="chargeruuid" value="'+result[i].uuid +'"/>';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">充电枪编号:</label><input type="text" disabled class="form-control" value="'+ result[i].chargerno +'"></div>';
                    dataHtml += '<div class=" col-md-4 col-sm-4 col-xs-4 "><label class="label-width1">枪资产编码:</label><input type="text" disabled class="form-control" value="'+ result[i].assetNo +'"></div>';

                    dataHtml += '<div class=" col-md-4 col-sm-4 col-xs-4 "><label class="label-width4">设备接口类型:</label><select class="form-control" name="type">';
                    if(equTypeList != null){
                        for(var k = 0;k<equTypeList.length; k++){
                            dataHtml += "<option value='"+equTypeList[k].constvalue+"'";
                            if(result[i].type == equTypeList[k].constvalue){
                                dataHtml += "selected";
                            }
                            dataHtml +=">"+equTypeList[k].constname+"</option>";
                        }
                    }
                    dataHtml += '</select></div></div><div class="col-md-12 form-group">';
                    dataHtml += '<div class="col-md-4 col-sm-4 col-xs-4"><label class="label-width1">关联停车位:</label><select class="form-control" name="parkSpaceSelect" style="border-radius: 4px 0px 0px 4px;width: 58%;">';
                    if(spaceList != null){
                        for (var j =0 ;j<spaceList.length;j++){
                            dataHtml +="<option value='"+spaceList[j].uuid+"'";
                            if( result[i].spaceuuid == spaceList[j].uuid){
                                dataHtml +=" selected";
                            }
                            if(result[i].bindedCharger == "1"){
                                dataHtml +=" title='该停车位已绑定，不可选择！' style='background-color: red;' disabled";
                            }
                            dataHtml +=">"+spaceList[j].name+"</option>";
                        }
                    }
                    dataHtml += '</select><button id="addParkSpaceClick" class="btn btn-info" style="border-radius: 0px 4px 4px 0px;vertical-align: top;width: 12%;"><i class="fa fa-plus"></i></button></div>';
                    dataHtml += '</div></div>';
                    nthTabs.addTab({
                        id:result[i].uuid,
                        title:"充电枪" + result[i].chargerno,
                        content:dataHtml
                    });
                    if(i == 0){
                        nthTabs.setActTab(result[i].uuid);
                    }
                };
            };
        },
        error:function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
};




// 设备接口类型初始化
var equTypeList = null;
function getEquTypeList(){
    $.ajax({
        url: projectPath + '/base/constss/list?code=1000000002',
        type: 'GET',
        dataType: 'json',
        async:false,
        success: function (data) {
            equTypeList = data.data
        },
        error: function () {
            layerAlert.errorMessage("出错了");
        }
    });
};


// 关联停车位初始化
var spaceList = null;
function getSpaceList(){
    $.ajax({
        url: projectPath + '/base/parking/spaces/listByArea?parkingAreaUuid=' + $("#parkareauuid").val(),
        type: 'POST',
        dataType: 'json',
        async:false,
        success: function (data) {
            spaceList = data.data
        },
        error: function () {
            layerAlert.errorMessage("出错了");
        }
    });
}

//桩修改 设备型号的查询
$("#equipmentClick").on("click",function () {
    $('#equipment_table').bootstrapTable('refresh', {url: projectPath + "/base/equipment/infos/list"});
    var index = layer.open({
        type: 1,
        title: "设备型号列表",
        shadeClose: true,
        shade: 0.3,
        area: ['90%', '100%'],
        skin: 'layui-layer-rims',
        content: $(".equipmentQuery"),
        closeBtn:1,
        shadeClose:false,
        fixed:false,
        resize:true,
        maxmin:true,
        btn:['确定','关闭'],
        success:function(){
            getEquipment();
        },
        yes:function(){
            var vendoruuid = "";
            var p_n = $('#equipment_table').bootstrapTable('getData');
            if (p_n != null && p_n.length > 0) {
                var len = $('#equipment_table').bootstrapTable('getData').length;
                for (var i = 0; i < len; i++) {
                    if ($('#equipment_table').bootstrapTable('getData')[i].check == true) {
                        vendoruuid = $('#equipment_table').bootstrapTable('getData')[i].vendoruuid; // 生产厂商uuid
                        vendorName = $('#equipment_table').bootstrapTable('getData')[i].vendorName; //  生产厂商
                        equipmodeluuid = $('#equipment_table').bootstrapTable('getData')[i].uuid; //  当前uuid
                        equipmentname = $('#equipment_table').bootstrapTable('getData')[i].equipmentname; // 设备型号
                        maxoutvolt = $('#equipment_table').bootstrapTable('getData')[i].maxoutvolt;
                        power = $('#equipment_table').bootstrapTable('getData')[i].power;
                    };
                };
                if (vendoruuid != '' && vendoruuid != null) {
                    $("#equipmentno").val(equipmentname);
                    $("#equipmentno").attr("datauuid",equipmodeluuid); // 设备型号 uuid
                    $("#vendoruuid").attr("datauuid",vendoruuid); //生产厂商 uuid
                    $("#vendoruuid").val(vendorName);
                    $("#maxoutvolt").val(maxoutvolt);
                    $("#power").val(power);
                } else {
                    layerAlert.errorMessage("您的选择为空");
                }
            };
            layer.close(index);
        },
        btn2:function(){
        },
        cancel:function () {
        }
    });
});
// 桩修改设备表格列表初始化
function getEquipment() {
    $('#equipment_table').bootstrapTable({
        method: 'GET',                      //请求方式（*）
        url: projectPath + "/base/equipment/infos/list",
        contentType: 'application/x-www-form-urlencoded',
        //toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search: false,
        queryParams: queryEquipTabParams,//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 15, 20],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "id",
        // showColumns: true,                  //是否显示所有的列
        // showRefresh: true,                  //显示刷新按钮
        // showToggle: true,
        minimumCountColumns: 12,             //最少允许的列数
        singleSelect: true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            {field: 'check', checkbox: true},
            {field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                var pageSize = $('#equipment_table').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber = $('#equipment_table').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }},
            {field: 'uuid', title: '主键', align: 'center', visible: false},
            {field: 'equipmentname', title: '类型名称', align: 'center', formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'type', title: '设备类型', align: 'center', formatter: function (value, row, index) {
                if (value == "2") {
                    value = "交流充电桩";
                } else if (value == "1") {
                    value = "直流充电桩";
                } else if (value == "3") {
                    value = "通用充电桩";
                } else {
                    value = "其他";
                }
                return '<div style="white-space: nowrap;">' + value + '</div>';
            }},
            {field: 'vendorName', title: '生产厂商', align: 'center', formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'power', title: '额定功率', align: 'center', formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "千瓦</div>";
            }},
            {field: 'minoutvolt', title: '最小输出电压', align: 'center', formatter: function (value, row, index) {
                if (value == "" || value == null) {
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'maxoutvolt', title: '最大输出电压', align: 'center', formatter: function (value, row, index) {
                if (value == "" || value == null) {
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'minoutcurrent', title: '最小输出电流', align: 'center', formatter: function (value, row, index) {
                if (value == "" || value == null) {
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'maxoutcurrent', title: '最大输出电流', align: 'center', formatter: function (value, row, index) {
                if (value == "" || value == null) {
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
        ],
        responseHandler: function (obj) {
            return {
                total: obj.data.total,
                rows: obj.data.list
            }
        }
    });
}
function queryEquipTabParams() {
    var filter_equipment_table = {};
    if($("#typeinfo").val() != "") {
        filter_equipment_table.type = $("#typeinfo").val();
    };
    if($("#qryEquipmentName").val() !=""){
        filter_equipment_table.equipmentName = $("#qryEquipmentName").val();
    };
    filter_equipment_table.offset = (this.pageNumber-1)*this.pageSize;
    filter_equipment_table.limit = this.pageSize;
    return filter_equipment_table;
};


//站选择事件触发
$("#stationClick").on("click",function () {
    var index = layer.open({
        type: 1,
        title: "充电站列表",
        shadeClose: true,
        shade: 0.3,
        area: ['90%', '100%'],
        skin: 'layui-layer-rims',
        content: $(".stationQuery"),
        closeBtn:1,
        shadeClose:false,
        fixed:false,
        resize:true,
        maxmin:true,
        btn:['确定','关闭'],
        success:function(){
        },
        yes:function(){
            var uuid = "";
            var p_n = $('#station_table').bootstrapTable('getData');
            if (p_n != null && p_n.length > 0) {
                var len = $('#station_table').bootstrapTable('getData').length;
                for (var i = 0; i < len; i++) {
                    if ($('#station_table').bootstrapTable('getData')[i].check == true) {
                        uuid = $('#station_table').bootstrapTable('getData')[i].uuid; // 站uuid
                        stationname = $('#station_table').bootstrapTable('getData')[i].stationname; // 站名称
                        standard = $('#station_table').bootstrapTable('getData')[i].standard; // 国标类型(充电标准)
                        tradetypes = $('#station_table').bootstrapTable('getData')[i].tradetypes; // 交易类型
                        partOrgName = $('#station_table').bootstrapTable('getData')[i].partOrgName; // 省市部门
                        stationtype = $('#station_table').bootstrapTable('getData')[i].stationtype;
                        address = $('#station_table').bootstrapTable('getData')[i].address; // 站地址
                        isthird = $('#station_table').bootstrapTable('getData')[i].isthird; // 三方
                        lat = $('#station_table').bootstrapTable('getData')[i].lat;
                        lng = $('#station_table').bootstrapTable('getData')[i].lng;
                        operatoruuid = $('#station_table').bootstrapTable('getData')[i].operatoruuid; // 运营商
                        servicephone = $('#station_table').bootstrapTable('getData')[i].servicephone;
                        prOrgName = $('#station_table').bootstrapTable('getData')[i].prOrgName;
                    };
                };
                if (uuid != '' && uuid != null) {
                    $("#stationnameInfo").val(stationname); // 站名称
                    $("#stationnameInfo").attr("uuid",uuid); // 站uuid

                    /*$("#standards").selectpicker('val',standard.split(",")); // 充电标准
                     $('#standards').selectpicker('refresh');
                     */

                    var standards = standard.split(",");

                    $("#standards").selectpicker('val',standards); // 充电标准

                    if(standards != ""){
                        $.each(standards,function(index,item){
                            $('#standards').find('[value='+standards[index]+']').prop('disabled', false);
                        });
                    }
                    $('#standards').selectpicker('refresh');


                    var groupCheckbox=$("input[name='tradeTypes']");
                    for(var i=0;i<groupCheckbox.length;i++){
                        if(isInArray(tradetypes,groupCheckbox[i].value)){
                            groupCheckbox[i].checked=true;
                            groupCheckbox[i].disabled=false;
                        }
                    }; // 交易类型

                    $("#provinceCityPartInfo").val(partOrgName); // 组织机构
                    $("#address").val(address); // 站地址
                    $("#isthird").val(isthird); // 三方
                    $("#stationType").selectpicker('val',((isthird==0||isthird==1)?"0":"1")+"-"+ stationtype); // 站点类型
                    $('#stationType').selectpicker('refresh');

                    $("#lat").val(lat); // 经度
                    $("#lng").val(lng); // 纬度
                    $('#operatoruuid').selectpicker('val', operatoruuid);//运营商设置选中
                    $('#operatoruuid').selectpicker('refresh');

                    $("#servicephone").val(servicephone); // 服务电话
                    $("#prorgCode").val(prOrgName); // 产权单位
                } else {
                    layerAlert.errorMessage("您的选择为空");
                }
            };

            $("#parkareauuid").val("");
            $("#parkAreaNameInfo").val("");
            $("#parkingfee").val("");
            $("#openat").val("");
            $("#closeat").val("");
            layer.close(index);
        },
        btn2:function(){

        },
        cancel:function () {

        }
    });
});
// 桩修改站表格列表初始化
$('#station_table').bootstrapTable({
    method: 'POST',                      //请求方式（*）
    url: projectPath+"/base/stations/list",
    contentType: 'application/x-www-form-urlencoded',
    toolbar: '#toolbar',                //工具按钮用哪个容器
    striped: true,                      //是否显示行间隔色
    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    pagination: true,                   //是否显示分页（*）
    sortable: false,                     //是否启用排序
    sortOrder: "asc",                   //排序方式
    search:false,
    queryParams: queryStationTabParams,//传递参数（*）
    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
    pageNumber: 1,                       //初始化加载第一页，默认第一页
    pageSize: 10,                       //每页的记录行数（*）
    pageList: [10, 15,20],        //可供选择的每页的行数（*）
    strictSearch: true,
    clickToSelect: true,                //是否启用点击选中行
    uniqueId: "id",
    // showColumns: true,                  //是否显示所有的列
    // showRefresh: true,                  //显示刷新按钮
    // showToggle: true,
    minimumCountColumns: 12,             //最少允许的列数
    singleSelect:true,
    paginationPreText: "上一页",
    paginationNextText: "下一页",
    columns: [
        {field: 'check', checkbox: true},
        {field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
            var pageSize=$('#station_table').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
            var pageNumber=$('#station_table').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
            return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
        }},
        {field: 'uuid', title: '主键', align: 'center', visible:false},
        {field: 'stationname', title: '充电站名称',align: 'center',formatter: function (value, row, index) {
            return '<div style="white-space: nowrap;">'+ value +'</div>';
        }},
        {field: 'stationno', title: '站编码',align: 'center',formatter: function (value, row, index) {
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'isthird', title: '是否第三方',align: 'center',formatter: function (value, row, index) {
            if(value == "0" || value == "1"){
                return "<div style='white-space: nowrap;'>否</div>";
            }else{
                return "<div style='white-space: nowrap;'>是</div>";
            };
        }},
        {field: 'lat', title: '经纬度',align: 'center',formatter: function (value, row, index) {
            return (row.lat+"/"+row.lng);
        }},
        {field: 'stationtype', title: '站类型',align: 'center',formatter:function(value, row, index){
            if(row.isthird == 0 || row.isthird == 1){
                switch(value){
                    //1高速,2城市公共,3单位内部,4公交,5其他,6出租车，99岸电
                    case 1:
                        value = "高速"
                        break;
                    case 2:
                        value ="城市公共"
                        break;
                    case 3:
                        value ="单位内部"
                        break;
                    case 4:
                        value ="公交"
                        break;
                    case 5:
                        value ="其他"
                        break;
                    case 6:
                        value ="出租车"
                        break;
                    case 99:
                        value ="岸电"
                        break;
                    default:value ="其他"
                }
            } else {
                switch(value){
                    //(1公共,50个人,100公交专用,101环卫专用,102物流专用,103出租车专用,255其他,99岸电)；
                    case 1:
                        value ="公共"
                        break;
                    case 50:
                        value ="个人"
                        break;
                    case 100:
                        value ="公交专用"
                        break;
                    case 101:
                        value ="环卫专用"
                        break;
                    case 102:
                        value ="物流"
                        break;
                    case 103:
                        value ="出租车"
                        break;
                    case 99:
                        value ="岸电"
                        break;
                    default:value ="其他"
                }
            }
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'stationstatus', title: '站状态', align: 'center',formatter: function (value, row, index) {
            if(value == "2"){
                return "<div style='white-space: nowrap;'>待投运</div>";
            }else if(value == "3"){
                return "<div style='white-space: nowrap;'>运行</div>";
            }else if(value == "8"){
                return "<div style='white-space: nowrap;'>维护</div>";
            }else if(value == "10"){
                return "<div style='white-space: nowrap;'>停运</div>";
            }else if(value == "11"){
                return "<div style='white-space: nowrap;'>退运</div>";
            }else{
                return "";
            }
        }},
        {field: 'servicecode', title: '内外部', align: 'center',formatter: function (value, row, index) {
            if(row.urposetype==2){
                if(value==1){
                    return "<div style='white-space: nowrap;'>公用-对外开放</div>";
                } else {
                    return "<div style='white-space: nowrap;'>公用-对内开放</div>";
                }
            } else {
                return "<div style='white-space: nowrap;'>专用-不展示</div>";
            }
        }},
        {field: 'provinceName', title: '省份',align: 'center',visible:false,formatter: function (value, row, index) {
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'cityName', title: '城市',align: 'center',visible:false,formatter: function (value, row, index) {
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'provinceOrgName', title: '省组织机构',align: 'center',formatter: function (value, row, index) {
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'cityOrgName', title: '市组织机构', align: 'center',formatter: function (value, row, index) {
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'prOrgName', title: '产权单位', align: 'center',formatter: function (value, row, index) {
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'managerOrgName', title: '运维单位', align: 'center',formatter: function (value, row, index) {
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'rundate', title: '投运时间', align: 'center',visible:false,formatter: function (value, row, index) {
            if(value == "" || value == null){
                value="";
            }else{
                value = getLocalTime(value);
            };
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }},
        {field: 'createdat', title: '最近更新时间', align: 'center',sortable:true,order:'desc',visible:false,formatter: function (value, row, index) {
            if(row.updatedat != '' && row.updatedat != null){
                value = row.updatedat;
            }
            if(value == "" || value == null){
                value="";
            }else{
                value = getLocalTime(value);
            }
            return "<div style='white-space: nowrap;'>" + value + "</div>";
        }}
    ],
    responseHandler: function (obj) {
        return {
            total:obj.data.total,
            rows:obj.data.data
        }
    }
});
function queryStationTabParams() {
    var filterinfo = {};
    if ($('#stationName').val() != '') {// 充电站名
        filterinfo.name = $("#stationName").val();
    };
    filterinfo.offset = (this.pageNumber-1)*this.pageSize;
    filterinfo.limit = this.pageSize;
    return filterinfo;
};


//停车区弹窗选择事件
$("#parkAreaClick").on("click",function () {
    var index = layer.open({
        type: 1,
        title: "充电站列表",
        shadeClose: true,
        shade: 0.3,
        area: ['90%', '90%'],
        skin: 'layui-layer-rims',
        content: $(".parkAreaQuery"),
        closeBtn:1,
        shadeClose:false,
        fixed:false,
        resize:true,
        maxmin:true,
        btn:['确定','关闭'],
        success:function(){
            getParkArea();
        },
        yes:function(){
            var uuid= "";
            var p_n = $('#parkArea_table').bootstrapTable('getData');
            if (p_n != null && p_n.length > 0) {
                var len = $('#parkArea_table').bootstrapTable('getData').length;
                for (var i = 0; i < len; i++) {
                    if ($('#parkArea_table').bootstrapTable('getData')[i].check == true) {
                        uuid = $('#parkArea_table').bootstrapTable('getData')[i].uuid; // 区uuid
                        name = $('#parkArea_table').bootstrapTable('getData')[i].name; // 区名称
                        parkingfee = $('#parkArea_table').bootstrapTable('getData')[i].parkingfee; // 收费标准
                        openat = $('#parkArea_table').bootstrapTable('getData')[i].openat; // 开放
                        closeat = $('#parkArea_table').bootstrapTable('getData')[i].closeat; // 开放
                    };
                };
                if (uuid != '' && uuid != null) {
                    $("#parkAreaNameInfo").val(name);// 选择停车区
                    $("#parkareauuid").val(uuid); // 区uuid
                    $("#parkareauuid").change();
                    $("#parkingfee").val(parkingfee); // 收费标准
                    $("#openat").val(openat); // 开放时间
                    $("#closeat").val(closeat); //关闭时间
                } else {
                    layerAlert.errorMessage("您的选择为空");
                }
            };
            layer.close(index);
        },
        btn2:function(){

        },
        cancel:function () {

        }
    });
});
// 桩修改 停车区列表初始化
function getParkArea(){
    $('#parkArea_table').bootstrapTable('refresh', {url: projectPath+  "/base/stations/qryParkingAreaListForStation?uuid=" + $("#stationnameInfo").attr("uuid")});
    $('#parkArea_table').bootstrapTable({
        method: 'POST',                      //请求方式（*）
        url:projectPath+  "/base/stations/qryParkingAreaListForStation?uuid=" + $("#stationnameInfo").attr("uuid"),//请求后台的URL（*）
        contentType: 'application/x-www-form-urlencoded',
        //toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: true,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search:false,
        queryParams: queryParkAreaParams,//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [3, 10,20],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "id",
        //showColumns: true,                  //是否显示所有的列
        //showRefresh: true,                  //显示刷新按钮
        //showToggle: true,
        minimumCountColumns: 2,             //最少允许的列数
        singleSelect:true,
        // height:500,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            {field: 'check', checkbox: true},
            {field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                var pageSize=$('#tb_ads').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber=$('#tb_ads').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }},
            {field: 'uuid', title: '主键', align: 'center', visible:false},
            {field: 'name', title: '停车区名称', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'openat', title: '营业开始时间', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'closeat', title: '营业关闭时间', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'parkingfee', title: '收费标准', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'parkingdesc', title: '停车区描述', align: 'center',formatter: function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }}
        ],
        responseHandler: function (obj) {
            return {
                total:obj.data.length,
                rows:obj.data
            }
        }
    });
}
function queryParkAreaParams() {
    var filterinfo = {};
    filterinfo.offset = (this.pageNumber-1)*this.pageSize;
    filterinfo.limit = this.pageSize;
    return filterinfo;
};


// 保存
function saveStake(){
    // 提交验证
    if($("#stakename").val() == ""){
        layerAlert.warnMessage("充电桩名称是必填项");
        return;
    };
    if($("#equipmentno").val() == ""){
        layerAlert.warnMessage("请选择设备型号");
    };
    if($("#stationnameInfo").val() == ""){
        layerAlert.warnMessage("请选择充电站");
        return;
    };
    if($("#parkAreaNameInfo").val() == ""){
        layerAlert.warnMessage("请选择停车区");
        return;
    };
    if(nthTabs == null){
        layerAlert.warnMessage("请添加充电枪");
        return;
    };
    var stakeParams = {};
    stakeParams.baseStake = {};
    stakeParams.baseStake.stakeno = $("#stakeNos").val(); // 桩编号
    stakeParams.baseStake.stakename = $("#stakename").val(); // 桩名称
    stakeParams.baseStake.runtime = $("#runtime").val(); // 投运时间
    stakeParams.baseStake.authcode = $("#authcode").val(); // 授权码
    stakeParams.baseStake.registrationuuid = $("#registrationuuid").val(); // 注册码
    stakeParams.baseStake.staketype = $("#stakeTypes").val(); // 桩类型
    stakeParams.baseStake.type = $("#typeinfo").val(); // 设备类型
    stakeParams.baseStake.debuggingtime = $("#debuggingtime").val(); // 调试时间
    stakeParams.baseStake.vendoruuid = $("#vendoruuid").attr("datauuid"); // 生产厂商uuid
    stakeParams.baseStake.equipmodeluuid = $("#equipmentno").attr("datauuid"); // 设备uuid
    stakeParams.baseStake.stationuuid = $("#stationnameInfo").attr("uuid"); // 充电站uuid
    stakeParams.baseStake.durableYears = $("#durableyears").val(); // 使用年限
    // updateNew



    stakeParams.productionDate = $("#createdat").val(); // 生产日期
    stakeParams.standard = $("#standard").val();   // 接口标准


    stakeParams.baseStake.isthird = $("#isthird").val(); // 三方
    stakeParams.baseStake.parkingareauuid = $("#parkareauuid").val(); // 区uuid
    stakeParams.baseStake.uuid = $("#targetuuid").val(); // 桩主键
    stakeParams.baseStake.status = $("#status").val(); // 桩标记

    if($("#standards").val()){
        stakeParams.baseStake.chargeStandard = $("#standards").val();
    }; //充电标准
    stakeParams.baseStake.tradetypes="";
    var groupCheckbox=$("input[name='tradeTypes']");
    var paramsTradeTypes = "";
    for(var i=0;i<groupCheckbox.length;i++){
        if(groupCheckbox[i].checked){
            paramsTradeTypes+= "," + groupCheckbox[i].value;
        };
    }; // 交易类型
    paramsTradeTypes = paramsTradeTypes.substring(1);
    stakeParams.baseStake.tradetypes = paramsTradeTypes;

    //新建枪
    var tablist = nthTabs.getTabList();
    stakeParams.chargers = new Array();

    for (var i = 0;i<tablist.length;i++){
        var chargerModifyBean = {charger:{}};
        chargerModifyBean.charger.uuid =  $(tablist[i].id+" input[name='chargeruuid']").val();
        chargerModifyBean.charger.type = $(tablist[i].id+" select[name='type']").val(); // 设备接口类型
        var spacename=$(tablist[i].id+" input[name='newAddParkSpaceName']").val();
        //名称不为空表示新增
        if(spacename && spacename!=''){
            chargerModifyBean.parkingSpace = {};
            chargerModifyBean.parkingSpace.name = spacename; // 新建停车位名称
        } else {
            //
            chargerModifyBean.charger.spaceuuid = $(tablist[i].id+" select[name='parkSpaceSelect']").val(); // 关联停车位
        }
        stakeParams.chargers.push(chargerModifyBean);
    };

    $.ajax({
        type: "POST",
        url:projectPath+'/base/stakes/update',
        dataType:"json",
        data:JSON.stringify(stakeParams),
        contentType:"application/json",
        success:function (data) {
            console.log(data)
            if(data.code == "0"){
                layerAlert.successMessage2("修改成功")
            }else{
                layerAlert.errorMessage("修改失败");
            }
        },
        error:function () {
            layerAlert.errorMessage("数据错误");
        }
    });
}

// 提交
function submitStake() {
    $.ajax({
        type: "POST",
        url:projectPath+'/base/workorders/maApplySubmit?workOrderUuid=' + $("#uuid").val(),
        dataType:"json",
        // data:JSON.stringify(stakeParams),
        contentType:"application/json",
        success:function (data) {
            if(data.code == "0"){
                layerAlert.successMessage("提交成功","");
            }else{
                layerAlert.errorMessage("提交失败");
            }
        },
        error:function () {
            layerAlert.errorMessage("数据错误");
        }
    });
}

// 设备类型
function selectList(id,code) {
    $.get(projectPath + '/base/constss/list?code='+code, function (r) {
        var data = r.data;
        var value = '<option value="">--请选择--</option>';
        $(data).each(function(index,r){
            value += '<option value="'+r.constvalue+'">'+r.constname+'</option>';
        })
        $("#" + id).append(value);
    });
};

function initOrgSelects(){
    // 运营商
    listOperatorSelect({selectid:'operatoruuid'});
    // 充电标准
    getSelectOptionsWithCode({code:'30029300',selectid:'standards',disabled:true});

}















































// 导出
$("#btnExport").on("click",function(){
    layer.open({
        type: 1,
        title: "选择导出页数",
        shadeClose: true,
        shade: 0.3,
        move :false,
        area: ['300px', '250px'],
        skin: 'layui-layer-rims',
        content: $(".export_dialog"),
        btn:['确定'],
        closeBtn:1,
        success:function(){
            $('.export_dialog').empty();
            //var endPage=pageCount;
            //var startPage=1;
            var str=[
                '<div class="form-group" style="margin-top:30px;margin-left: 10px;">',
                '<label class="label-width3">起始页:</label><input type="text"  class="form-control" id="start_page" value="1" />',
                '</div>',
                '<div class="form-group" style="margin-top: 10px;margin-left: 10px;">',
                '<label class="label-width3">结束页:</label><input type="text"  class="form-control" id="end_page" value="1000"/>',
                '</div>',
            ].join('');
            $('.export_dialog').append(str);
        },
        close:function(){
            $('.export_dialog').remove(str);
        },
        btn1:function(){
            alert("导出成功");
        }
    });
});